package com.gscitysfy.cus.drain.utils;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName LoadBalancerUtil
 * @Description: 判断feign是否正常访问
 * @Author: wuxinxin
 * @CreateDate: 2022/5/20 15:55
 * @Version: 1.0
 */
@Component
public class LoadBalancerUtil {

    // 注入LoadBalancerClient
    @Resource
    LoadBalancerClient loadBalancerClient;

    /**
     * 通过 LoadBalancer 获取提供服务的host与ip
     */
    public String getService(String serviceId)
    {
        //获取实例服务中的某一个服务
        ServiceInstance instance = loadBalancerClient.choose(serviceId);
        if(null == instance){
            return null;
        }
        //获取服务的ip地址和端口号
        String host = instance.getHost();
        int port = instance.getPort();
        //格式化最终的访问地址
        return String.format("http://%s:%s", host, port);
    }
}
